from django.shortcuts import render
from .models import Product,Job,Suite,Step
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from ETP.forms import ProductForm,JobForm,SuiteForm,APIStepForm,UIStepForm
from django.http import HttpResponseRedirect,Http404,HttpResponse
from django.urls import reverse
from .tasks import hello_word,runMysuite
from djcelery.models import PeriodicTask,CrontabSchedule,IntervalSchedule
import json

def runHello(request):
    hello_word.delay()
    return HttpResponse('yiyunxing')


# Create your view here.

@login_required
def products(request):

    user = request.user
    print(user.id)
    #product_member = Product.objects.filter(member__username=user.username)
    #print(product_member)
    products = Product.objects.filter(Q(owner=request.user) or Q(member__username__contains=request.user) or Q(member_leader=request.user) or Q(participant_leader=request.user) or Q(participant__username__contains=request.user))
    #products = Product.objects.filter(Q(member__username=user.username))
    #products = Product.objects.filter(Q(member_leader=request.user))
    #products = Product.objects.filter(Q(participant__username=request.user))
    #products = Product.objects.filter(Q(participant_leader=request.user))
    #products = Product.objects.raw("SELECT * FROM etp_product WHERE member_leader_id = 1 or owner_id = 1 OR participant_leader_id = 1")
    print(products)
    context = {'products':products}
    return render(request, 'ETP/products.html',context)


def product(request,product_id):
    product = Product.objects.filter(id=product_id)
    jobs = Job.objects.filter(product_id=product_id)
    context = {'product':product,'jobs':jobs}
    return render(request,'ETP/product.html',context)


def new_product(request):
    if request.method != "POST":
        form = ProductForm()
    else:
        form = ProductForm(request.POST)
        if form.is_valid():
            new_product = form.save(commit=False)
            new_product.owner = request.user
            new_product.save()
            form.save_m2m()#M2M关系要求先保存父对象，而不是通过使用commit=False，需要在后边添加form.save_m2m()
            return HttpResponseRedirect(reverse('ETP:products'))
    context = {'form':form}
    return render(request,'ETP/new_product.html',context)


def edit_product(request,product_id):
    product = Product.objects.get(id=product_id)
    if request.method != 'POST':
        form = ProductForm(instance=product)
    else:
        form = ProductForm(instance=product,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('ETP:products'))
    context = {'product':product,'form':form}
    return render(request,'ETP/edit_product.html',context)


def delete_product(request,product_id):
    product = Product.objects.get(id=product_id)
    product.member.clear()
    product.participant.clear()
    product.delete()
    return HttpResponseRedirect(reverse('ETP:products'))


def new_job(request,product_id):
    print(product_id)
    product = Product.objects.get(id = product_id)
    if request.method != 'POST':
        form = JobForm()
    else:
        form = JobForm(data=request.POST)
        new_job = form.save(commit=False)
        new_job.product = product
        new_job.save()
        return HttpResponseRedirect(reverse('ETP:product',args=[product_id]))
    context = {'product':product,'form':form}
    return render(request,'ETP/new_job.html',context)


def edit_job(request,job_id):
    print(job_id)
    job = Job.objects.get(id = job_id)
    print(job)
    product = job.product

    if request.method != 'POST':
        form = JobForm(instance=job)
    else:
        form = JobForm(instance=job,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('ETP:product',args=['product.id']))
    context = {'job':job,'product':product,'form':form}
    return render(request,'ETP/edit_job.html',context)



def delete_job(request,job_id):
    job = Job.objects.get(id=job_id)
    product = job.product
    job.delete()
    return HttpResponseRedirect(reverse('ETP:product',args=[product.id]))


def job(request,job_id):
    job = Job.objects.get(id=job_id)
    productID = job.product.id
    suites = Suite.objects.filter(job_id=job_id)
    context = {'product':productID,'job': job, 'suites': suites}
    return render(request, 'ETP/job.html', context)


def new_suite(request,job_id):
    job = Job.objects.get(id = job_id)
    if request.method != 'POST':
        form = SuiteForm()
    else:
        form = SuiteForm(data=request.POST)
        new_suite = form.save(commit=False)
        new_suite.create_time = '1990-09-09'
        new_suite.job = job
        new_suite.save()
        return HttpResponseRedirect(reverse('ETP:job',args=[job_id]))
    context = {'job':job,'form':form}
    return render(request,'ETP/new_suite.html',context)


def suite(request,suite_id):
    suite = Suite.objects.get(id=suite_id)
    jobID = suite.job.id
    steps = Step.objects.filter(suite_id=suite_id).order_by("run_order")
    context = {'job':jobID,'suite':suite,'steps':steps}
    return render(request,'ETP/suite.html',context)


def edit_suite(request,suite_id):
    suite = Suite.objects.get(id=suite_id)
    job = suite.job
    if request.method != 'POST':
        form = SuiteForm(instance=suite)
    else:
        form = SuiteForm(instance=suite,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('ETP:job',args=[job.id]))
    context = {'job':job,'suite':suite,'form':form}
    return render(request,'ETP/edit_suite.html',context)


def delete_suite(request,suite_id):
    suite = Suite.objects.get(id=suite_id)
    job = suite.job
    suite.delete()

    return HttpResponseRedirect(reverse('ETP:job',args=[job.id]))

def new_apistep(request,suite_id):
    suite = Suite.objects.get(id=suite_id)
    steps = Step.objects.filter(suite_id=suite_id).order_by("run_order")
    if request.method != 'POST':
        form = APIStepForm()
    else:
        form = APIStepForm(data=request.POST)
        new_step = form.save(commit=False)
        new_step.suite=suite
        new_step.run_order = steps.count() + 1
        new_step.save()
        return HttpResponseRedirect(reverse('ETP:suite',args=[suite_id]))
    context = {
        'form':form,
        'suite':suite
    }
    return render(request, 'ETP/new_apistep.html', context)


def new_uistep(request,suite_id):
    suite = Suite.objects.get(id=suite_id)
    steps = Step.objects.filter(suite_id=suite_id).order_by("run_order")
    if request.method != 'POST':
        form = UIStepForm()
    else:
        form = UIStepForm(data=request.POST)
        new_step = form.save(commit=False)
        new_step.suite = suite
        new_step.run_order = steps.count() + 1
        new_step.save()
        return HttpResponseRedirect(reverse('ETP:suite',args=[suite_id]))
    context = {
        'form':form,
        'suite':suite,
    }
    return render(request,'ETP/new_uistep.html',context)


def edit_apistep(request,step_id):

    step = Step.objects.get(id=step_id)
    suiteID = step.suite_id
    suite = Suite.objects.get(id=suiteID)
    if request.method != 'POST':
        form = APIStepForm(instance=step)
    else:
        form = APIStepForm(instance=step, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('ETP:suite', args=[suiteID]))
    context = {'step':step,'suite': suite, 'form': form}
    return render(request, 'ETP/edit_apistep.html', context)


def edit_uistep(request,step_id):
    print(step_id)
    step = Step.objects.get(id=step_id)

    suiteID = step.suite_id
    print(suiteID)
    suite = Suite.objects.get(id=step.suite_id)
    if request.method != 'POST':
        form = UIStepForm(instance=step)
    else:
        form = UIStepForm(instance=step,data=request.POST)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect(reverse('ETP:suite',args=[suiteID]))
    context = {'step':step,'suite':suite,'form':form}
    return render(request,'ETP/edit_uistep.html',context)


def delete_step(request,step_id):
    step = Step.objects.get(id=step_id)
    suite = step.suite
    step.delete()
    return HttpResponseRedirect(reverse('ETP:suite',args=[suite.id]))



def run_suite(request,suite_id):
    suite = Suite.objects.get(id=suite_id)
    job = suite.job
    productID = job.product.id
    suites = Suite.objects.filter(job_id=job.id)
    context = {'product':productID,'job': job, 'suites': suites}
    runMysuite.delay(suite_id)
    return HttpResponseRedirect(reverse('ETP:job',args=[job.id]))


def getUsers(request):
    users = User.objects.all()
    data = []
    for user in users:
        resuser = {
            'user_id':user.id,
            'user_name':user.username
        }
        data.append(resuser)
    resusers = json.dumps(data)
    print(resusers)
    return HttpResponse(resusers,content_type='application/json,charset=utf-8')